"""
应用相关的数据模型
- App: 应用基本信息表，存储所有可用的应用
- UserInstalledApp: 用户安装的应用表，记录用户安装的应用及其配置
"""

from datetime import datetime, UTC
from sqlalchemy import Column, String, Boolean, DateTime, Integer, JSON, ForeignKey, Float, text
from sqlalchemy.orm import relationship
from dao.postgresql_connect import Base

class App(Base):
    """应用基本信息表"""
    __tablename__ = 'apps'

    id = Column(String(36), primary_key=True)
    key = Column(String, unique=True, nullable=False, comment='应用唯一标识符')
    name = Column(String, nullable=False, comment='应用名称')
    icon = Column(String, nullable=False, comment='应用图标')
    description = Column(String, nullable=False, comment='应用描述')
    category = Column(String, nullable=False, comment='应用分类')
    tags = Column(JSON, default=list, comment='应用标签')
    is_published = Column(Boolean, default=False, comment='是否已发布')
    published_at = Column(DateTime, comment='发布时间')
    version = Column(String, nullable=False, comment='应用版本')
    config = Column(JSON, default=dict, comment='应用配置')
    pricing = Column(JSON, default=dict, comment='定价信息')
    created_by = Column(String(36), ForeignKey('users.id'), nullable=False, comment='创建者ID')
    created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False, comment='创建时间')
    updated_at = Column(DateTime, default=lambda: datetime.now(UTC), server_default=text('CURRENT_TIMESTAMP'), nullable=False, comment='更新时间')

    # 关系
    creator = relationship('User', back_populates='created_apps')
    installed_apps = relationship('UserInstalledApp', back_populates='app')
    chat_sessions = relationship('ChatSession', back_populates='app')
    stats = relationship('AppStats', back_populates='app')
    quotas = relationship('UserQuota', back_populates='app')

class UserInstalledApp(Base):
    """用户安装的应用表""" 
    __tablename__ = 'user_installed_apps'

    id = Column(String(36), primary_key=True)
    user_id = Column(String(36), ForeignKey('users.id'), nullable=False, comment='用户ID')
    app_id = Column(String(36), ForeignKey('apps.id'), nullable=False, comment='应用ID')
    api_key = Column(String, comment='用户配置的API密钥')
    custom_config = Column(JSON, default=dict, comment='用户自定义配置')
    last_used_at = Column(DateTime, comment='最后使用时间')
    created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False, comment='安装时间')
    updated_at = Column(DateTime, default=lambda: datetime.now(UTC), server_default=text('CURRENT_TIMESTAMP'), nullable=False, comment='更新时间')

    # 关系
    user = relationship('User', back_populates='installed_apps')
    app = relationship('App', back_populates='installed_apps') 